package com.eshop.aspect;

import org.slf4j.LoggerFactory;
import org.aspectj.lang.annotation.Around;
import java.lang.reflect.Method;
import com.eshop.config.datasource.DynamicDataSourceContextHolder;
import com.eshop.annotation.DataSource;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.core.annotation.Order;
import org.aspectj.lang.annotation.Aspect;

// 动态切换数据源
@Aspect
@Order(1)
@Component
public class DataSourceAspect
{
    private static final Logger log;
    
    @Pointcut("@annotation(com.eshop.annotation.DataSource)")
    public void dsPointCut() {
    }
    
    @Around("dsPointCut()")
    public Object around(final ProceedingJoinPoint point) throws Throwable {
        final MethodSignature signature = (MethodSignature)point.getSignature();
        final Method method = signature.getMethod();
        final DataSource dataSource = method.getAnnotation(DataSource.class);
        if (dataSource != null) {
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
        }
        try {
            return point.proceed();
        }
        finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
    
    static {
        log = LoggerFactory.getLogger((Class)DataSourceAspect.class);
    }
}
